package com.cxx.purchasecharge.component.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cxx.purchasecharge.component.bean.ActionResult;
import com.cxx.purchasecharge.component.bean.ActionResult.ActionResultStatus;
import com.cxx.purchasecharge.component.bean.ContactBean;
import com.cxx.purchasecharge.component.bean.DataGridRequestForm;
import com.cxx.purchasecharge.component.bean.GenericPagingResult;
import com.cxx.purchasecharge.component.bean.LoginUser;
import com.cxx.purchasecharge.component.bean.PCApplicationContext;
import com.cxx.purchasecharge.component.utils.AjaxUtils;
import com.cxx.purchasecharge.component.utils.BeanConvertUtils;
import com.cxx.purchasecharge.component.utils.ComponentConstants;
import com.cxx.purchasecharge.component.utils.MessageProperties;
import com.cxx.purchasecharge.core.model.persistence.Contact;
import com.cxx.purchasecharge.service.PersistenceService;
import com.cxx.purchasecharge.service.QueryService;

@Controller
@RequestMapping ("/contact")
public class ContactManager extends GenericController <ContactBean>
{
    private static final Logger logger = Logger.getLogger (ContactManager.class);

    @Autowired
    private QueryService queryService;
    @Autowired
    private PersistenceService persistenceService;
    @Autowired
    private PCApplicationContext pcContext;

    public ContactManager ()
    {
        super.setViewName("contactManagement");
    }

    @Override
    public String checkExist(@RequestParam String contaId, @RequestParam String contactName, HttpServletRequest request)
    {
        if (StringUtils.isBlank (contaId))
        {
            // new
            Contact contact = queryService.getContact (contactName);
            if (null != contact)
            {
                return "false";
            }
        }
        else
        {
            // edit
            long id = Long.parseLong (contaId);
            Contact contact = queryService.getContact (contactName);
            if (null != contact && contact.getId () != id)
            {
                return "false";
            }
        }
        return "true";
    }

    @Override
    public String getAllModel(DataGridRequestForm dataGridRequestForm, HttpServletRequest request)
    {
        logger.debug (dataGridRequestForm);
        int page = dataGridRequestForm.getPage () - 1;
        int size = dataGridRequestForm.getRows ();
        String sortField = parseSortField (dataGridRequestForm.getSort ());
        String order = dataGridRequestForm.getOrder ();
        Pageable pageable = new PageRequest (page, size, new Sort ("asc".equalsIgnoreCase (order) ? Direction.ASC
                                                                                                 : Direction.DESC,
                                                                   sortField));
        String searchKey = (null == dataGridRequestForm.getSearchKey () ? "" : dataGridRequestForm.getSearchKey ()
                                                                                                  .trim ());
        LoginUser loginUser = null;
        try
        {
            loginUser = pcContext.getLoginUser (request);
        }
        catch (Exception e)
        {
            logger.warn("Get login user failed", e);
        }
        
        if (null != loginUser)
        {
            String signUser = loginUser.isAdmin () ? "" : loginUser.getUserId ();
            Page <Contact> contactPage = queryService.findContactByFuzzy (pageable, searchKey, signUser, loginUser.isAdmin ());
            List <Contact> contactList = contactPage.getContent ();
            long total = contactPage.getTotalElements ();
            GenericPagingResult <ContactBean> contactPagingResult = new GenericPagingResult <ContactBean> ();
            contactPagingResult.setRows (BeanConvertUtils.contactList2ContactBeanList (contactList));
            contactPagingResult.setTotal (total);

            JSONObject jsonObject = JSONObject.fromObject (contactPagingResult);
            return jsonObject.toString ();
        }
        return "";
    }

    @Override
    public void getModelByIdWithResponse(@RequestParam String id, HttpServletResponse response) throws Exception
    {
        if (StringUtils.isNotBlank (id))
        {
            response.setContentType ("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter ();

            Contact contact = queryService.getContact (Long.parseLong (id));
            String html = "<style type='text/css'>" + ".dv-table td{border:0;}"
                          + ".dv-label{font-weight:bold;color:#15428B;width:150px;}" + "</style>";

            html += "<table class='dv-table' border='0' style='width:100%;'>";
            html += "<tr><td class='dv-label'>" + "Contact Name:" + "</td><td>" + contact.getName ()
                    + "</td><td class='dv-label'>" + "Phone:" + "</td><td>" + contact.getMobilePhone () + "</td></tr>";
            html += "<tr><td class='dv-label'>" + "Address:" + "</td><td>" + contact.getAddress ()
                    + "</td><td class='dv-label'>" + "Gender:" + "</td><td>" + contact.getGenderCode () + "</td></tr>";
            html += "<tr><td class='dv-label'>" + "Concerned Business:" + "</td><td>" + contact.getConcernedBusiness ()
                    + "</td><td class='dv-label'>" + "QQ:" + "</td><td>" + contact.getQq () + "</td></tr>";
            html += "</table>";

            writer.write (html);
        }
    }

    @Override
    public String addModel(@Valid ContactBean bean, BindingResult result, HttpServletRequest request)
    {
        if (result.hasErrors ())
        {
            logger.error (result.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                Contact contact = BeanConvertUtils.contactBean2Contact (bean);
                LoginUser loginUser = pcContext.getLoginUser (request);
                String operator = loginUser.getUserId ();
                persistenceService.addContact (contact);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_ADD_FAIL,
                                                                                       ComponentConstants.MSG_CONTACT))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @Override
    public String updateModel(@Valid ContactBean bean, BindingResult result, HttpServletRequest request)
    {
        if (result.hasErrors ())
        {
            logger.error (result.getAllErrors ());
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                Contact contact = BeanConvertUtils.contactBean2Contact (bean);
                LoginUser loginUser = pcContext.getLoginUser (request);
                String operator = loginUser.getUserId ();
                persistenceService.updateContact (contact);
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_UPDATE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
    }

    @Override
    public String deleteModels(@RequestParam String ids, HttpServletRequest request)
    {
        if (null != ids && ids.trim ().length () > 0)
        {
            List <Contact> contacts = new ArrayList <Contact> ();
            Contact contact;
            if (ids.indexOf (";") != -1)
            {
                String[] idArr = ids.split (";");
                for (String typeId : idArr)
                {
                    contact = new Contact ();
                    contact.setId (Long.parseLong (typeId));
                    contacts.add (contact);
                }
            }
            else
            {
                contact = new Contact ();
                contact.setId (Long.parseLong (ids));
                contacts.add (contact);
            }

            ActionResult ar = ActionResult.createActionResult ().build ();
            try
            {
                LoginUser loginUser = pcContext.getLoginUser (request);
                String operator = loginUser.getUserId ();
                StringBuilder sb = new StringBuilder ();
                for (Contact contacter : contacts)
                {
                    if(null != queryService.getCustomerByContact (contacter.getId ())) 
                    {
                        sb.append (contacter.getId () + ",");
                    }
                    else 
                    {
                        persistenceService.deleteContact (contacter);
                    }
                }
                ar = ActionResult.ok ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT))
                                 .build ();
            }
            catch (Exception e)
            {
                logger.error (e.getMessage (), e);
                ar = ActionResult.serverError ()
                                 .withMessage (MessageProperties.getConfigFormatted (ComponentConstants.GENERIC_MSG_DELETE_SUCCESS,
                                                                                       ComponentConstants.MSG_CONTACT))
                                 .build ();
            }
            return AjaxUtils.getJsonObject (ar);
        }
        else
        {
            logger.error (ActionResultStatus.BAD_REQUEST + " ids=" + ids + " when delete contact");
            ActionResult ar = ActionResult.badRequest ()
                                          .withMessage (MessageProperties.getConfig (ComponentConstants.GENERIC_MSG_REQUEST_ARGS_ERROR))
                                          .build ();
            return AjaxUtils.getJsonObject (ar);
        }
    }

    private String parseSortField (final String sortField)
    {
        String sortFieldAfterParse = "name";
        if (!StringUtils.isBlank (sortField))
        {
            sortFieldAfterParse = sortField;
            if (ComponentConstants.PHONE.equalsIgnoreCase (sortField))
            {
                sortFieldAfterParse = ComponentConstants.MOBILE_PHONE;
            }
            else if (ComponentConstants.TECENT_QQ.equalsIgnoreCase (sortField))
            {
                sortFieldAfterParse = ComponentConstants.QQ;
            }
            else if (ComponentConstants.CUSTOMER_NAME.equalsIgnoreCase (sortField))
            {
                sortFieldAfterParse = ComponentConstants.CUSTOMER_DOT_SHORT_NAME;
            }
            else if (ComponentConstants.CONTACT_TYPE.equalsIgnoreCase (sortField))
            {
                sortFieldAfterParse = ComponentConstants.TYPE_DOT_NAME;
            }
        }
        return sortFieldAfterParse;
    }

}
